package controllers

import (
	"gitchina/kly_service/errors"
	"gitchina/kly_service/models"
	"gitchina/kly_service/util"
	"io/ioutil"

	"time"

	"fmt"

	"bytes"

	"strings"

	"github.com/astaxie/beego"
)

type MediaController struct {
	beego.Controller
}

// @router /110001 [post]
func (m *MediaController) UploadAudio() {

	maxAudioSize := beego.AppConfig.DefaultInt("maxAudioSize", 1048576)
	cdn := beego.AppConfig.String("audioCdn")
	bn := beego.AppConfig.String("ossAudioBucketName")
	location := beego.AppConfig.String("audioStoreLocation")

	if f, h, err := m.GetFile("uploadaudio"); err == nil {
		if audio, err := ioutil.ReadAll(f); err == nil {
			if len(audio) <= maxAudioSize {
				fn := strings.TrimRight(fmt.Sprintf("%d.%s", time.Now().Unix(), getAudioExt(h.Header.Get("Content-Type"))), ".")
				if store, err := models.NewStore(location); err == nil {
					if err := store.Options("bucketname", bn).
						Options("fn", fn).
						Save(bytes.NewBuffer(audio)); err == nil {
						m.Data["json"] = models.NewOkResponse(fmt.Sprintf("%s%s", cdn, fn))
					} else {
						util.GetLogger().Error("[ctl.audio.upload] - error:%s", err.Error())
						m.Data["json"] = models.NewFailResponse(errors.New(errors.MSG_Audio_Upload_Error))
					}
				} else {
					util.GetLogger().Error("[ctl.audio.upload] - error:%s", err.Error())
					m.Data["json"] = models.NewFailResponse(errors.New(errors.MSG_Audio_Upload_Error))
				}
			} else {
				util.GetLogger().Error("[ctl.audio.upload] - unexpected audio size: %d or size > %d", len(audio), maxAudioSize)
				m.Data["json"] = models.NewFailResponse(errors.New(errors.MSG_Audio_Invalid_Size))
			}
		} else {
			util.GetLogger().Error("[ctl.audio.upload] - error:%s", err.Error())
			m.Data["json"] = models.NewFailResponse(errors.New(errors.MSG_Audio_Not_Found))
		}
	} else {
		util.GetLogger().Error("[ctl.audio.upload] - error: %s", err.Error())
		m.Data["json"] = models.NewFailResponse(errors.New(errors.MSG_Audio_Not_Found))
	}
	m.ServeJSON()
}

func getAudioExt(contentType string) string {
	switch contentType {
	case "audio/aac":
		return "aac"
	case "audio/amr":
		return "amr"
	case "audio/mp3":
		return "mp3"
	case "audio/ogg":
		return "ogg"
	default:
		return ""
	}
}
